package com.mayflygeek.mayflyask.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mayflygeek.mayflyask.entity.User;
import com.mayflygeek.mayflyask.service.SendEmailService;
import com.mayflygeek.mayflyask.service.UserService;
import com.mayflygeek.mayflyask.util.Constants;
import com.mayflygeek.mayflyask.util.MD5Utils;
/**
 * @author 蝈蝈 
 * @email guodefu909@126.com
 * @team 蜉蝣极客
 * @link www.mayflygeek.com
 * 登录Controller
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController {
	
	private Logger log = LoggerFactory.getLogger(getClass());

	@Resource
	private UserService userService;
	
	@Resource
	private SendEmailService sendEmailService;
	
	@Resource
	private HttpSession session;
	
	
//	跳转登录页
	@RequestMapping(value = "/toLogin")
	public String toLogin() {
		log.info("toLogin");
		return "login";
	}
	
//	登出
	@RequestMapping(value = "/logout")
	public String logout() {
		log.info("logout");
		session.removeAttribute(Constants.SESSION_USER);
		return Constants.TOLOGIN;
	}
	
//	登录
	@RequestMapping(value = "")
	public String login(User user,ModelMap model) {
		if (user==null || user.getUserName()==null ||user.getPassword()==null) {
			return Constants.TOLOGIN;
		}
		User userRuselt = userService.getByUserName(user.getUserName());
		if (userRuselt != null) {
			user.setPassword(MD5Utils.encode(user.getPassword() + userRuselt.getSalt()));
			if (userRuselt.getPassword().equals(user.getPassword())) {
				Boolean rememberMe = user.getRememberMe();
				if (rememberMe!=null && rememberMe) {
					userRuselt.setRememberMe(rememberMe);
				}
				session.setAttribute(Constants.SESSION_USER,userRuselt);
				return "redirect:toIndexPage";
			}
		}
		model.addAttribute("message","用户名或密码不正确！");
		model.addAttribute("user", user);
		return Constants.TOLOGIN;
	}
	
	
	
}
